package com.liangdemo.web.Service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangdemo.web.Service.UserService;
import com.liangdemo.web.mapper.AccountMapper;
import com.liangdemo.web.model.Account;
import com.liangdemo.web.model.DTO.RegisterDTO;
import com.liangdemo.web.model.User;
import com.liangdemo.web.model.UserData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @author Mr.Liang
 * @date 2022/4/24 16:49
 */
@Service
public class AccoutService extends ServiceImpl<AccountMapper, Account> {
    @Autowired
    private UserService userService;
    @Autowired
    private UserDateService userDateService;

    /**
     * 查询用户手机号是否存在
     *
     * @param phone
     * @return
     */
    private boolean accountIsExist(String phone) {
        Optional<Account> account = this.lambdaQuery().eq(Account::getPhone, phone).oneOpt();
        return account.isPresent();
    }


    public String register(RegisterDTO registerDTO) {
        /**
         * 查询用户手机号是否存在
         */
        if (accountIsExist(registerDTO.getPhone())) {
            return "该手机号已存在";
        } else if (!StringUtils.equals(registerDTO.getPassword(), registerDTO.getConfirmPassword())) {
            /*判断用户两次输入的密码是否一致*/
            return "两次密码输入的不一致";
        }
        User user = new User();
        user.setUserName(registerDTO.getPhone());
        userService.save(user);

        Account account = new Account();
        account.setEmail(registerDTO.getEmail());
        account.setPhone(registerDTO.getPhone());
        account.setUserId(String.valueOf(user.getId()));
        account.setAccount(registerDTO.getAccount());
        account.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes(StandardCharsets.UTF_8)));
        this.save(account);

        UserData userData = new UserData();
        userData.setUserId(String.valueOf(user.getId()));
        userData.setPhone(registerDTO.getPhone());
        userData.setEmail(registerDTO.getEmail());
        userData.setAccountId(account.getId());
        userDateService.save(userData);


        return "账户创建成功";
    }
}
